#include "MyFileTools.h"
#include <iostream>
#include <fstream>

std::string FileTools::ReadAll(const std::string &filePath)
{
    std::ifstream f(filePath);
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败\n";
        return {};
    }
    f.seekg(0, std::ios::end);
    ;
    long size = f.tellg();
    f.seekg(0, std::ios::beg);
    char *p = new char[size + 1]; //+1放\0
    // std::string data;
    f.read(p, size);
    std::string data = p;
    f.close();
    delete[] p;

    return data;
}

std::vector<std::string> FileTools::ReadLine(const std::string &filePath)
{
    std::ifstream f(filePath);
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败\n";
        return {};
    }
    std::vector<std::string> vec;
    while (f.eof() == false)
    {
        std::string LineData;
        std::getline(f, LineData);
        // 过滤空行,getline会自己将空行滤掉
        if (LineData != "")
            vec.push_back(std::move(LineData)); // 移动语义,减少拷贝,夺取内存
    }
    f.close();
    return vec;
}

bool FileTools::WriteToFile(const std::string &filePath, const std::string &data)
{
    std::ofstream f(filePath); // 这里要检查下
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败\n";
        return {};
    }
    f.write(data.c_str(), data.size());
    // f << data;
    f.close();
    return true;
}

bool FileTools::AppendToFile(const std::string &filePath, const std::string &data)
{
    std::ofstream f(filePath, std::ios::app);
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败\n";
        return {};
    }
    f.write(data.c_str(), data.size());
    // f << data;
    f.close();
    return true;
}

bool FileTools::AppendLine(const std::string &filePath, std::vector<std::string> &strVec)
{
    std::ofstream f(filePath, std::ios::app);
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败！\n";
        return false;
    }
    for (auto &str : strVec)
    {
        f.write(str.c_str(), str.size());
        f << "\n";
    }
    f.close();
    return true;
}

bool FileTools::WriteLine(const std::string &filePath, std::vector<std::string> &strVec)
{
    std::ofstream f(filePath); // 这里要检查下
    if (!f.is_open())
    {
        std::cout << filePath << "打开失败\n";
        return false;
    }
    for (auto &str : strVec)
    {
        f.write(str.c_str(), str.size());
        f << "\n";
    }

    // f << data;
    f.close();
    return true;
}
